package com.punch.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.punch.common.dto.system.ActivityDTO;
import com.punch.common.exception.BusinessException;
import com.punch.common.page.PageInfo;
import com.punch.common.query.syste.ActivityQueryInfo;
import com.punch.common.simple.redis.utils.UserUtil;
import com.punch.common.tools.BasePage;
import com.punch.common.utils.ImageUtil;
import com.punch.common.vo.system.ActivityVO;
import com.punch.system.exception.SysExceptionEnum;
import com.punch.system.mapper.SysActivityMapper;
import com.punch.system.model.SysActivity;
import com.punch.system.model.SysNationArea;
import com.punch.system.service.ActivityService;
import com.punch.system.service.NationAreaService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.StringJoiner;

/**
 * <p>
 * 系统活动表 服务实现类
 * </p>
 *
 * @author wjj
 * @since 2020-12-14
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<SysActivityMapper, SysActivity> implements ActivityService {


    @Resource
    private NationAreaService nationAreaService;

    /**
     * 活动列表
     *
     * @param queryInfo 查询条件
     * @return PageInfo<ActivityVO>
     */
    @Override
    public PageInfo<ActivityVO> listActivity(ActivityQueryInfo queryInfo) {
        queryInfo.setSortStr("update_time");
        queryInfo.setCurrentAreaId(UserUtil.getLoginUser().getAreaId());
        return BasePage.queryBasePage(queryInfo, params -> this.getBaseMapper().queryCount(params),
                params -> {
                    List<ActivityVO> retList = getBaseMapper().queryList(params);
                    retList.forEach(activityVO -> {
                        if (activityVO.getStatus() == 0) {
                            activityVO.setUpdateTime(null);
                        }
                    });
                    return retList;
                });
    }

    /**
     * 保存活动
     *
     * @param activityDTO 提交表单
     * @return id
     */
    @Override
    public Integer saveActivity(ActivityDTO activityDTO) {
        SysActivity activity = new SysActivity();
        //设置父地区
        Integer areaId = activityDTO.getAreaId();
        SysNationArea area = nationAreaService.getById(areaId);
        activity.setAllAreaIds(area.getParentIds() + "," + areaId);
        BeanUtil.copyProperties(activityDTO, activity);
        //处理活动图片前缀
        if (StrUtil.isNotEmpty(activityDTO.getActivityImg())) {
            String img = ImageUtil.removePrefix(activityDTO.getActivityImg());
            activity.setActivityImg(img);
        }
        //活动介绍
        if (CollUtil.isEmpty(activityDTO.getImageList())) {
            activity.setIntroduceImg("");
        } else {
            StringJoiner sj = new StringJoiner(",");
            activityDTO.getImageList().forEach((img) -> sj.add(ImageUtil.removePrefix(img)));
            activity.setIntroduceImg(sj.toString());
        }
        Long userId = UserUtil.getLoginUserId();
        activity.setCreateId(userId);
        if (!save(activity)) {
            throw new BusinessException(SysExceptionEnum.DATA_INSERT_EXCEPTION);
        }
        return activity.getId();
    }

    /**
     * 修改活动
     *
     * @param activityDTO 提交表单
     * @return id
     */
    @Override
    public Integer updateActivity(ActivityDTO activityDTO) {
        SysActivity activity = new SysActivity();
        BeanUtil.copyProperties(activityDTO, activity);
        //介绍图片
        if (CollUtil.isEmpty(activityDTO.getImageList())) {
            activity.setIntroduceImg("");
        } else {
            StringJoiner sj = new StringJoiner(",");
            activityDTO.getImageList().forEach((img) -> sj.add(ImageUtil.removePrefix(img)));
            activity.setIntroduceImg(sj.toString());
        }

        //处理活动图片前缀
        if (StrUtil.isNotEmpty(activityDTO.getActivityImg())) {
            String img = ImageUtil.removePrefix(activityDTO.getActivityImg());
            activity.setActivityImg(img);
        }
        activity.setId(activityDTO.getActivityId());
        if (!updateById(activity)) {
            throw new BusinessException(SysExceptionEnum.DATA_UPDATE_EXCEPTION);
        }
        return activity.getId();
    }

    /**
     * 活动详情
     *
     * @param activityId activityId
     * @return ActivityVO
     */
    @Override
    public ActivityVO getActivity(Integer activityId) {
        SysActivity activityEX = getById(activityId);
        Optional.ofNullable(activityEX).orElseThrow(() -> new BusinessException(SysExceptionEnum.DATA_NOT_EXIST));
        ActivityVO activityVO = new ActivityVO();
        BeanUtil.copyProperties(activityEX, activityVO);
        //介绍图片
        if (StrUtil.isNotEmpty(activityEX.getIntroduceImg())) {
            String[] split = activityEX.getIntroduceImg().split(",");
            List<String> imgList = new ArrayList<>();
            for (String img : split) {
                imgList.add(ImageUtil.addPrefix(img));
            }
            activityVO.setImageList(imgList);
        }
        if (StrUtil.isNotEmpty(activityEX.getActivityImg())) {
            activityVO.setActivityImg(ImageUtil.addPrefix(activityEX.getActivityImg()));
        }
        activityVO.setActivityId(activityId);
        return activityVO;
    }

    /**
     * 删除活动
     *
     * @param activityId activityId
     * @return id
     */
    @Override
    public Integer deleteActivity(Integer activityId) {
        SysActivity activityEX = getById(activityId);
        Optional.ofNullable(activityEX).orElseThrow(() -> new BusinessException(SysExceptionEnum.DATA_NOT_EXIST));
        //已经展示的不能删除,需要下架
        if (activityEX.getStatus() == 1) {
            throw new BusinessException(SysExceptionEnum.STATUS_ERROR);
        }
        if (!removeById(activityId)) {
            throw new BusinessException(SysExceptionEnum.DATA_DELETION_EXCEPTION);
        }
        return activityId;
    }

    /**
     * 修改活动状态
     *
     * @param activityId activityId
     * @param status     状态 0-不显示 1-显示
     * @return bannerId
     */
    @Override
    public Integer updateActivityStatus(Integer activityId, Integer status) {
        SysActivity activityEX = getById(activityId);
        Optional.ofNullable(activityEX).orElseThrow(() -> new BusinessException(SysExceptionEnum.DATA_NOT_EXIST));
        if (activityEX.getStatus().equals(status)) {
            throw new BusinessException(SysExceptionEnum.STATUS_ERROR);
        }
        SysActivity activity = new SysActivity();
        activity.setStatus(status);
        activity.setId(activityId);
        if (!updateById(activity)) {
            throw new BusinessException(SysExceptionEnum.DATA_UPDATE_EXCEPTION);
        }
        return activityId;
    }
}
